# clean environment
rm(list=ls())

# load packages
library(ggplot2)

# load data set with parliamentary inquiries
dat <- read.csv("inquiries.csv")

# create filler variable to sum over
dat$one <- 1

# aggregate number of inquiries by extremism category and party
shares_df <- aggregate(one ~ extremism_v + party, data=dat, FUN=sum)

# calculate the total number of inquriries by party
shares_df$total <- ave(shares_df$one, shares_df$party, FUN=sum) 

# share by party
shares_df$share <- shares_df$one/shares_df$total

# category factor with factor levels 
shares_df$extremism_v <- factor(shares_df$extremism_v, levels=c("right", "left", "both", "unclear", "neither"))

# english names of parties
shares_df$party_eng <- NA
shares_df$party_eng[shares_df$party=="AFD"] <- "AfD"
shares_df$party_eng[shares_df$party=="CDU"] <- "CDU/CSU"
shares_df$party_eng[shares_df$party=="FDP"] <- "FDP"
shares_df$party_eng[shares_df$party=="GRUENE"] <- "Greens"
shares_df$party_eng[shares_df$party=="LINKE"] <- "Left Party"
shares_df$party_eng[shares_df$party=="SPD"] <- "SPD"

# generate string varoable with party name and number of inquiries
shares_df$party_N <- paste0(shares_df$party_eng, " (N=", shares_df$total, ")")

# plot
ggplot(data=shares_df, aes(x=extremism_v, y=share*100)) + 
  geom_bar(stat="identity") + 
  #  theme_classic() +
  theme_bw() +
  ylab("Percent") + xlab("") +
  facet_wrap(~party_N) + 
  scale_x_discrete(labels=c("RWE", "LWE", "Both", "Unclear")) +
  theme(text=element_text(size=15)) +
  theme(panel.grid = element_blank())

ggsave("Fig3_4.pdf", width=7, height=5)
